#pragma once

#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <ctime>
#include <cstdlib>

#define TaskNum 3
typedef void(*task_t)();
task_t tasks[TaskNum];

void Print() { std::cout << "task: Print()" << std::endl; }
void Download() { std::cout << "task: Download()" << std::endl; }
void Flush() { std::cout << "task: Flush()" << std::endl; }

void LoadTask()
{
    srand(time(nullptr) ^ getpid() ^ 1777); // 随机数种子，尽量随机一些
    tasks[0] = Print;
    tasks[1] = Download;
    tasks[2] = Flush;
}

int SelectTask()
{
    return (rand() % TaskNum);
}

void ExcuteTask(int n)
{
    if (n < 0 || n >= TaskNum) return;
    tasks[n]();
}

void work()
{
    while(1)
    {
        int command = 0;
        int n = read(0, &command, sizeof(command));
        if (n == sizeof(int))
        {
            std::cout << "pid: " << getpid() << ", handle task" << std::endl;
            ExcuteTask(command);
        }
        else if (n == 0)
        {
            // 读取到文件末尾，写端已经关闭，那么读端也关闭
            std::cout << "sub process: " << getpid() << ", quit" << std::endl;
            break;
        }
    }
}